///
global without sharing class AdjustPriceHandler {

/*
    WebService static String adjustPrice(String adId) {
            SavePoint sp = Database.setSavepoint();
            try {
                 // FIXME 审批只会一条一条来，所以允许在for循环里面写soql
                List<AdjustPriceProduct__c> fromList = [select Id, AdjustTo__c, AdjustSalesPrice__c from AdjustPriceProduct__c where AdjustPrice__c = :adId];
                Map<Id, AdjustPriceProduct__c> appMap = new Map<Id, AdjustPriceProduct__c>();
                for (AdjustPriceProduct__c app : fromList) {
                    appMap.put(app.AdjustTo__c, app);
                }

                List<ContractProduct__c> toList = [select Id from ContractProduct__c where Id in :appMap.keySet()];
                
                for (ContractProduct__c cp : toList) {
                    cp.SalesPrice__c = appMap.get(cp.Id).AdjustSalesPrice__c;
                    cp.PriceChanged__c = true;
                    cp.IsSycToNc__c = false;
                    // qp.Quantity__c = qpMap.get(qp.Id).Quantity__c;
                    // qp.Comment__c = qpMap.get(qp.Id).Comment__c;
                }
                update toList;
                return 'ok';
            }
            catch (Exception e) {
                Database.rollback(sp);
                return e.getMessage();
            }


     }

     */
     /*
    public static String adjustContract(String conid ){

         Contract__c con = [select Id,OwnerId ,Corpcode__c,Account__c,TerminalCustomer__c  from Contract__c where Id=:conid];

         String terminalId = con.TerminalCustomer__c == null ? con.Account__c : con.TerminalCustomer__c;
         
          List<ContractReagentInformation__c> cpList = [select ReagentProducts__c,WhetherReverse__c,
                                                  ReagentProducts__r.NCCode__c, Price__c  from ContractReagentInformation__c
                                                where Contract__c = :conid  and WhetherReverse__c = false ];

           if(cpList.size() == 0)return 'NO DATA';
           Map<String,String> companyMap = ImportObject.getPicklistValues('Contract__c', 'Corpcode__c', true);

          String salescode = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false).get(companyMap.get(con.Corpcode__c ));
          Set<Id> prodsets = new Set<Id>();
          
          for (ContractReagentInformation__c qp : cpList) {

              prodsets.add(qp.ReagentProducts__c );
            
          }
         Map<String,PriceList__c> priceListMap = new Map<String,PriceList__c>();

        for (PriceList__c p :[select Id ,ApplicableCustomers__c,Product__c,Price__c,SalesCode__c  from PriceList__c where  Account__c =:con.Account__c  and  SalesCode__c =:salescode and Product__c in:prodsets ] ) {
            
              priceListMap.put(p.Product__c+'-'+p.SalesCode__c+'-'+p.ApplicableCustomers__c ,p);   

        }

        SavePoint sp = Database.setSavepoint();
        try {
        List<PriceList__c> plList = new List<PriceList__c>();
            for (ContractReagentInformation__c cp: cpList) {

                 PriceList__c pl = null;
                 String key = cp.ReagentProducts__c +'-'+salescode+ '-'+terminalId ;
                if(priceListMap.containsKey(key)){

                    pl = priceListMap.get(key);

                }else{

                    pl = new PriceList__c();
                    pl.Product__c = cp.ReagentProducts__c;
                    pl.SalesCode__c = salescode;
                    pl.Account__c = con.Account__c;
                    
                    pl.ApplicableCustomers__c = terminalId;

                }
                  pl.Company__c = companyMap.get(con.Corpcode__c);
                  pl.Price__c =  cp.Price__c ;
                  pl.OwnerId = con.OwnerId;

                  plList.add(pl);



            }
            System.debug('+++'+plList);

           if(plList.size() >0) upsert plList;
            for ( ContractReagentInformation__c cp : cpList) {
                cp.WhetherReverse__c = true ;
            }

              if(cpList.size() > 0 ) update cpList;
              return 'ok';

        }catch (Exception e) {
            Database.rollback(sp);
            return '写入到价目表错误:'+e.getMessage();
        }


        

     }
     */

     public static void  adjustOpp(String oppid  ){

         Opportunity opp = [select Id,OwnerId ,Corpcode__c,AccountId ,TerminalCustomer__c  from Opportunity where Id=:oppid];

         String terminalId = opp.TerminalCustomer__c == null ? opp.AccountId : opp.TerminalCustomer__c;
         
          List<ContractReagentInformation__c> cpList = [select ReagentProducts__c,WhetherReverse__c,
                                                  ReagentProducts__r.NCCode__c, Price__c  from ContractReagentInformation__c
                                                where Opportunity__c = :oppid  and WhetherReverse__c = false ];

           if(cpList.size() == 0)return;

           Map<String,String> companyMap = ImportObject.getPicklistValues('Opportunity', 'Corpcode__c', true);

          String salescode = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false).get(companyMap.get(opp.Corpcode__c ));
          Set<Id> prodsets = new Set<Id>();
          
          for (ContractReagentInformation__c qp : cpList) {

              prodsets.add(qp.ReagentProducts__c );
            
          }
         Map<String,PriceList__c> priceListMap = new Map<String,PriceList__c>();

        for (PriceList__c p :[select Id ,ApplicableCustomers__c,Product__c,Price__c,SalesCode__c  from PriceList__c where  Account__c =:opp.AccountId   and  SalesCode__c =:salescode and Product__c in:prodsets ] ) {
            
              priceListMap.put(p.Product__c+'-'+p.SalesCode__c+'-'+p.ApplicableCustomers__c ,p);   

        }

        SavePoint sp = Database.setSavepoint();
        try {
        List<PriceList__c> plList = new List<PriceList__c>();
            for (ContractReagentInformation__c cp: cpList) {

                 PriceList__c pl = null;
                 String key = cp.ReagentProducts__c +'-'+salescode+ '-'+terminalId ;
                if(priceListMap.containsKey(key)){

                    pl = priceListMap.get(key);

                }else{

                    pl = new PriceList__c();
                    pl.Product__c = cp.ReagentProducts__c;
                    pl.SalesCode__c = salescode;
                    pl.Account__c = opp.AccountId ;
                    
                    pl.ApplicableCustomers__c = terminalId;

                }
                  pl.Company__c = companyMap.get(opp.Corpcode__c);
                  pl.Price__c =  cp.Price__c ;
                  pl.OwnerId = opp.OwnerId;

                  plList.add(pl);



            }
            System.debug('+++'+plList);

           if(plList.size() >0) upsert plList;
            for ( ContractReagentInformation__c cp : cpList) {
                cp.WhetherReverse__c = true ;
            }

              if(cpList.size() > 0 ) update cpList;

        }catch (Exception e) {
            Database.rollback(sp);
            throw new DmlException('写入到价目表错误:'+e.getMessage());
        }


        

     }


    public static void toPriceList(List<AdjustPrice__c> aplist ,Map<Id,AdjustPrice__c> oldMap){


         Id rid  = Utils.getRecordTypeIdByDevNameAndObjName('PriceAdjustmentOversea', 'AdjustPrice__c');
         Map<String,String> accMap =new Map<String,String>();
        for (AdjustPrice__c ap  : aplist) {

            if(ap.Account__c != null )accMap.put(ap.Account__c, null );

        }
        if(!accMap.isEmpty()){

             for(Account acc : [select Id,Name  from Account where Id =:accMap.keySet()]){
                  accMap.put(acc.Id , acc.Name);
             }
             

        }
        for (AdjustPrice__c ap  : aplist) {

            AdjustPrice__c old = oldMap.get(ap.Id);
            if(old == null ) old = new AdjustPrice__c();

            if(ap.Status__c == '已批准'  && old.Status__c != ap.Status__c){
               
                if(ap.RecordTypeId == rid ){
                   adjustAboardPriceToPriceList(ap.Id );
                }

                if(accMap.get(ap.Account__c ) != null  && accMap.get(ap.Account__c).contains('报价/调价专用')){
                    adjustPriceToPriceList1(ap.Id);
                }

            }

        }



    }
     //计算明细中是否有自产产品
  
    public static void calcZc(Map<Id,AdjustPrice__c> qM ){
        Map<Id,String>tMap = new Map<Id,String>();
       for(AdjustPriceProduct__c qp :  [select AdjustPrice__c,Product__r.Brand__c,Product__r.Category1__c,Product__r.Category0__c ,Product__r.NCCode__c  from AdjustPriceProduct__c where AdjustPrice__c in:qM.keySet() ]){
               String type= tMap.get(qp.AdjustPrice__c);
             if( MaccuraBrandUtil.maccura.contains(qp.Product__r.Brand__c) || MaccuraBrandUtil.maccura.contains(qp.Product__r.NCCode__c)  || (qp.Product__r.Category1__c == '生化' &&  qp.Product__r.Category0__c == '仪器' )  ) {
                 type = (type == null ||  !type.contains('非自产') ) ? '自产' :'自产/非自产';
             }else{
                 type = ( type == null || type == '非自产') ? '非自产' :'自产/非自产';
             }
            tMap.put(qp.AdjustPrice__c, type );
       }

       for ( AdjustPrice__c q : qM.values() ) {
           q.ZC__c = tMap.get(q.Id);
       }



    }

/*
    public static String adjustQuoteToPriceList (String qId){
        Quote q = [select Id,OwnerId,Opportunity.AccountId ,Type__c,Opportunity.RecordType.DeveloperName  ,Opportunity.Owner.SubCompany__c,Opportunity.ExecutiveCompany__c ,Opportunity.ExecutiveCompany__r.RecordType.DeveloperName from Quote where Id=:qId];
        if(q.Type__c == '仪器报价')return '仪器报价不能反写到价目表!';
        Id accId = q.Opportunity.ExecutiveCompany__r.RecordType.DeveloperName == 'Maccura' ? q.Opportunity.AccountId : q.Opportunity.ExecutiveCompany__c ; 
        if(q.Opportunity.RecordType.DeveloperName == 'DealerOpportunity'||q.Opportunity.RecordType.DeveloperName == 'OverseaDearlerOpportunity')accId = q.Opportunity.AccountId;

        List<QuoteProduct__c> qList = [select Id,Product__c ,SalesPrice__c from QuoteProduct__c where Quote__c =:q.Id];

        if(qList.size() == 0)return 'NO DATA';
        String salescode = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false).get(q.Opportunity.Owner.SubCompany__c);
          Set<Id> prodsets = new Set<Id>();
        for (QuoteProduct__c qp : qList) {
          prodsets.add(qp.Product__c);
            
        }
         Map<String,PriceList__c> priceListMap = new Map<String,PriceList__c>();
        for (PriceList__c p :[select Id ,Product__c,Price__c,SalesCode__c  from PriceList__c where  Account__c =:accId and  SalesCode__c =:salescode and Product__c in:prodsets ] ) {
              priceListMap.put(p.Product__c+'-'+p.SalesCode__c ,p);     
        }
        SavePoint sp = Database.setSavepoint();
        try {
        List<PriceList__c> plList = new List<PriceList__c>();
            for (QuoteProduct__c qp: qList) {

                 PriceList__c pl = null;
                if(priceListMap.containsKey(qp.Product__c +'-'+salescode )){
                    pl = priceListMap.get(qp.Product__c +'-'+salescode);
                }else{
                    pl = new PriceList__c();
                    pl.Product__c = qp.Product__c;
                    pl.SalesCode__c = salescode;
                    pl.Account__c = accId;
                    pl.Company__c = q.Opportunity.Owner.SubCompany__c;


                }
             
                  pl.Price__c =  qp.SalesPrice__c ;
                  pl.OwnerId = q.OwnerId;
                  pl.Quote__c =  q.Id ;
                  plList.add(pl);



            }
            System.debug('+++'+plList);

           if(plList.size() >0) upsert plList;
             q.WhetherReverse__c = true;
              update q;
              return 'OK';

        }catch (Exception e) {
            Database.rollback(sp);
            return '写入到价目表错误:'+e.getMessage();
        }

    }
*/
    // 海外关联产品的价目表自动生成
    /*
      Map<Nccode ,PriceList> 
      Map<Nccode,Nccodes>

    */

    public static List<PriceList__c> genRelatedProductList(Map<String,PriceList__c> priceMap, Map<String,String> codeMap,String salescode,String accId ){


        Set<String> nccodes = new Set<String>();
        Map<String,String> nccodeMap = new Map<String,String>();
        for (String nccode   :codeMap.keySet() ) {

            for(String c : codeMap.get(nccode).split('\\*')){

               nccodes.add(c);
               nccodeMap.put(c,nccode);

            }
           

        }
        Set<Id> priceSet = new Set<Id>();
        for (PriceList__c p  :priceMap.values() ) {
            if(p.Id != null )priceSet.add(p.Id);
        }

        //查找产品
        Map<String,Id>productMap =new Map<String,Id>();
        for(Product__c p : [select Id,NCcode__c from Product__c where NCcode__c in:nccodes and RecordType.DeveloperName = 'NCProduct']){ 
            productMap.put(p.NCCode__c,p.Id);
        }

        //查找价格
        Map<String,Id> priceListMap = new Map<String,Id>();
        for (PriceList__c p :[select Id ,Product__r.NCCode__c from PriceList__c
         where  Account__c =:accId and  SalesCode__c =:salescode  and  Product__r.NCCode__c in:nccodes ] ) {
              priceListMap.put(p.Product__r.NCCode__c ,p.Id );     
        }

        List<PriceList__c> pL = new List<PriceList__c>();
        for (String nccode  : nccodes) {
            
            //如果价格已经存在
            if(priceMap.containsKey(nccode))continue;

            String productId = productMap.get(nccode);

              //如果没有匹配到产品
            if(String.isBlank(productId))continue;

            String currentCode = nccodeMap.get(nccode);
            //如果没匹配到原价格
            if(String.isBlank(currentCode))continue;

            PriceList__c p  = priceMap.get(currentCode);

            PriceList__c np = p.clone();
            np.Id = priceListMap.get(nccode);
            if(priceSet.contains(np.Id))continue;
            np.Product__c = productId;

            pl.add(np);


        }


        System.debug(pL);
        return pL;



    }

    public static String adjustAboardQuoteToPriceList (String qId){
        Quote q = [select Id,OwnerId,Opportunity.AccountId,Opportunity.OwnerId   ,Opportunity.Owner.SubCompany__c from Quote where Id=:qId];
        String accId = q.Opportunity.AccountId;
        String sql = 'select Id,Product__c,Product__r.RelatedProducts__c,Product__r.NCCode__c ,CooperativePrice__c,PrototypePrice__c ,BuyingPrice__c  from QuoteProduct__c where Quote__c =\''+qId+'\' ';

        // if(isEquip) sql += ' and Product__r.Category3__c not in ' + Label.RegentCatagory3;
        //if(!isEquip) sql += ' and Product__r.Category3__c in ' + Label.RegentCatagory3;

        List<QuoteProduct__c> qList = Database.query(sql);

        if(qList.size() == 0)return 'NO DATA';
        Map <String,String> salescodeMap =  ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false);
          String swsalescode = salescodeMap.get('迈克生物股份有限公司');
         // String dzsalescode = salescodeMap.get('迈克医疗电子有限公司');
          String salescode = swsalescode ;// isEquip ?dzsalescode: swsalescode;
          Set<Id> prodsets = new Set<Id>();
          for (QuoteProduct__c qp : qList) {
            prodsets.add(qp.Product__c);
            
          }
         Map<String,PriceList__c> priceListMap = new Map<String,PriceList__c>();
        for (PriceList__c p :[select Id ,Product__r.Category0__c,Product__c,CooperativePrice__c,PrototypePrice__c ,BuyingPrice__c,SalesCode__c  from PriceList__c where  Account__c =:accId and  SalesCode__c =:salescode  and  Product__c in:prodsets ] ) {
              priceListMap.put(p.Product__c+'-'+p.SalesCode__c ,p);     
        }

        //SavePoint sp = Database.setSavepoint();
        
          Map<String,String> codeMap = new Map<String,String>();
          List<PriceList__c> plList = new List<PriceList__c>();
          Map<String,PriceList__c> priceMap = new Map<String,PriceList__c>();
            for (QuoteProduct__c qp: qList) {

                if(qp.Product__r.RelatedProducts__c != null )codeMap.put(qp.Product__r.NCCode__c, qp.Product__r.RelatedProducts__c);
                 PriceList__c pl = null;
                if(priceListMap.containsKey(qp.Product__c +'-'+salescode )){
                    pl = priceListMap.get(qp.Product__c +'-'+salescode);
                }else{
                    pl = new PriceList__c();
                    pl.Product__c = qp.Product__c;
                    pl.SalesCode__c = salescode;
                   

                }
                 pl.Company__c = q.Opportunity.Owner.SubCompany__c;
                  pl.Account__c = accId;
                  pl.CooperativePrice__c =  qp.CooperativePrice__c ;
                  pl.PrototypePrice__c =  qp.PrototypePrice__c ;
                  pl.ApplicableCustomers__c = accId;

                  pl.BuyingPrice__c =  qp.BuyingPrice__c ;
                  pl.OwnerId = q.Opportunity.OwnerId ;
                  pl.Quote__c =  q.Id ;
                  plList.add(pl);
                  if(qp.Product__r.NCCode__c != null) priceMap.put(qp.Product__r.NCCode__c, pl);



            }
            System.debug('+++'+plList);
            if(!codeMap.isEmpty() && !priceMap.isEmpty()) plList.addAll(genRelatedProductList(priceMap,codeMap,salescode,accId));
           if(plList.size() >0) upsert plList;
             // q.WhetherReverse__c = true;
             //  update q;
            return 'ok';

      

    }
/*
     public static String adjustMeasuerToPriceList (String mId){
       Measure_Calculate__c mc = [select Id ,Opportunity__r.OwnerId,Company__c,Opportunity__r.AccountId,Opportunity__r.ExecutiveCompany__c ,Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName from Measure_Calculate__c where Id=:mId];
       Boolean isDealer = mc.Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName != 'Maccura';
        Id accId = isDealer ?mc.Opportunity__r.ExecutiveCompany__c : mc.Opportunity__r.AccountId ; 

        List<Measure_Calculate_Product__c> qList = [select Id,Product__c ,SalesPriceWT__c,DealerInstCost__c from Measure_Calculate_Product__c where Measure_Calculate__c =:mc.Id and IsEquipRelated__c = false ];

        if(qList.size() == 0)return 'NO DATA';
        String salescode = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false).get(mc.Company__c);
          Set<Id> prodsets = new Set<Id>();
        for (Measure_Calculate_Product__c mcp : qList) {
          prodsets.add(mcp.Product__c);
            
        }
         Map<String,PriceList__c> priceListMap = new Map<String,PriceList__c>();
        for (PriceList__c p :[select Id ,Product__c,Price__c,SalesCode__c  from PriceList__c where  Account__c =:accId and  SalesCode__c =:salescode and Product__c in:prodsets ] ) {
              priceListMap.put(p.Product__c+'-'+p.SalesCode__c ,p);     
        }
        SavePoint sp = Database.setSavepoint();
        try {
        List<PriceList__c> plList = new List<PriceList__c>();
            for (Measure_Calculate_Product__c mcp : qList) {

                 PriceList__c pl = null;
                if(priceListMap.containsKey(mcp.Product__c +'-'+salescode )){
                    pl = priceListMap.get(mcp.Product__c +'-'+salescode );
                }else{
                    pl = new PriceList__c();
                    pl.Product__c = mcp.Product__c;
                    pl.SalesCode__c = salescode;
                    pl.Account__c = accId;
                    pl.Company__c = mc.Company__c;

                }
             
                  pl.Price__c =    mcp.SalesPriceWT__c ;
                  pl.OwnerId = mc.Opportunity__r.OwnerId;
                  pl.Measure_Calculate__c = mc.Id ;
                  plList.add(pl);



            }
            System.debug('+++'+plList);

           if(plList.size() >0) upsert plList;
            mc.WhetherReverse__c = true;
              update mc;
              return 'OK';

        }catch (Exception e) {
            Database.rollback(sp);
            return '写入到价目表错误:'+e.getMessage();
        }



    }

*/

     public  static String adjustAboardPriceToPriceList (String apId){

        //SavePoint sp = Database.setSavepoint();
       // try {


            AdjustPrice__c ap = [select Id, Company__c,WhetherReverse__c ,WhetherRegentReverse__c ,OwnerId ,SalesCode__c ,Account__c from AdjustPrice__c where Id=:apId];

              List<AdjustPriceProduct__c> appList = new List<AdjustPriceProduct__c>();
              String sql = 'select Product__c,Product__r.RelatedProducts__c,Product__r.NCCode__c ,PresentPrice__c,PurchasePriceNow__c from AdjustPriceProduct__c where AdjustPrice__c =\''+apId+'\' ';

              appList = Database.query(sql);

              if(appList.size() == 0)return 'NO DATA';
               Map <String,String> salescodeMap =  ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false);
              String swsalescode = salescodeMap.get('迈克生物股份有限公司');
              //String dzsalescode = salescodeMap.get('迈克医疗电子有限公司');
              String salescode = swsalescode;//isEquip ? dzsalescode: swsalescode;

              Set<Id> prodsets = new Set<Id>();
              for ( AdjustPriceProduct__c app: appList ) {
                    prodsets.add(app.Product__c);              
              }
              Map<String,PriceList__c> priceListMap = new Map<String,PriceList__c>();
              for (PriceList__c p :[select Id ,Product__c,Price__c,SalesCode__c  from PriceList__c where  Account__c =:ap.Account__c  and Product__c in:prodsets ] ) {
                    priceListMap.put(p.Product__c+'-'+p.SalesCode__c ,p);     
              }
              Map<String,String> codeMap = new Map<String,String>();

              Map<String,PriceList__c> priceMap = new Map<String,PriceList__c>();
              List<PriceList__c >plList = new List<PriceList__c>();
              for (AdjustPriceProduct__c app: appList) {
                    
                    if(app.Product__r.RelatedProducts__c != null )codeMap.put(app.Product__r.NCCode__c, app.Product__r.RelatedProducts__c);

                       PriceList__c pl = null;
                    if(priceListMap.containsKey(app.Product__c +'-'+salescode )){
                        pl = priceListMap.get(app.Product__c +'-'+salescode);
                    }else{
                        pl = new PriceList__c();
                      
                        pl.Product__c = app.Product__c;
                        pl.SalesCode__c = salescode;
                        pl.JustPriceProduct__c = app.Id;
                       

                    }
                      pl.Account__c = ap.Account__c;

                     pl.Company__c = ap.Company__c;
                 
                      pl.CooperativePrice__c =  app.PresentPrice__c;
                      pl.BuyingPrice__c =  app.PurchasePriceNow__c ;
                      pl.OwnerId = ap.OwnerId;
                      plList.add(pl);
                      if(app.Product__r.NCCode__c != null )priceMap.put(app.Product__r.NCCode__c, pl);



              }

              if(!codeMap.isEmpty() && !priceMap.isEmpty()) plList.addAll(genRelatedProductList(priceMap,codeMap,salescode,ap.Account__c));
              System.debug('+++'+plList);
              if(plList.size() >0) upsert plList;
       
            return 'ok';
    } 
     public  static String adjustPriceToPriceList (String apId ){

        SavePoint sp = Database.setSavepoint();
        try {

             AdjustPrice__c ap = adjustPriceToPriceList1(apId );
            ap.WhetherReverse__c = true;
            update ap;
            return 'OK';
              /*String terminalId = ap.ApplicableCustomers__c == null ? ap.Account__c : ap.ApplicableCustomers__c;

              List<AdjustPriceProduct__c> appList = new List<AdjustPriceProduct__c>();
              appList = [select Product__c,OriginalPrice__c,AdjustSalesPrice__c  from AdjustPriceProduct__c where AdjustPrice__c =:apId];

              if(appList.size() == 0)return 'NO DATA';

              Set<Id> prodsets = new Set<Id>();
              for ( AdjustPriceProduct__c app: appList ) {
                    prodsets.add(app.Product__c);              
              }
              Map<String,PriceList__c> priceListMap = new Map<String,PriceList__c>();
              for (PriceList__c p :[select Id ,Product__c,Price__c,SalesCode__c ,ApplicableCustomers__c  from PriceList__c where  Account__c =:ap.Account__c and  SalesCode__c =:ap.SalesCode__c and Product__c in:prodsets ] ) {
                    
                    priceListMap.put(p.Product__c+'-'+p.SalesCode__c+'-'+p.ApplicableCustomers__c ,p);     
              }
              
              List<PriceList__c> plList = new List<PriceList__c>();
              for (AdjustPriceProduct__c app: appList) {

                     PriceList__c pl = null;
                   
                     String key = app.Product__c +'-'+ap.SalesCode__c +'-'+terminalId;

                    if(priceListMap.containsKey(key)){

                        pl = priceListMap.get(key );
                    }else{
                        pl = new PriceList__c();
                        pl.Product__c = app.Product__c;
                        pl.SalesCode__c = ap.SalesCode__c;
                        pl.JustPriceProduct__c = app.Id;
                        pl.Account__c = ap.Account__c;
                        

                        pl.ApplicableCustomers__c = terminalId;

                    }
                      pl.Company__c = ap.Company__c;
                 
                      pl.Price__c =  app.AdjustSalesPrice__c;
                      pl.OwnerId = ap.OwnerId;
                      plList.add(pl);



              }


                  
              
              if(plList.size() >0) upsert plList;
              System.debug('+++'+plList);
              ap.WhetherReverse__c = true;
              update ap;
              return 'OK';*/

        }catch (Exception e) {
            Database.rollback(sp);
            return '写入到价目表错误:'+e.getMessage();
        }
        
    
            
    }  

    public  static AdjustPrice__c  adjustPriceToPriceList1 ( String apId ){

               AdjustPrice__c ap = [select Id,ApplicableCustomers__c, Company__c,WhetherReverse__c ,OwnerId ,SalesCode__c ,Account__c from AdjustPrice__c where Id=:apId];

              String terminalId = ap.ApplicableCustomers__c == null ? ap.Account__c : ap.ApplicableCustomers__c;

              List<AdjustPriceProduct__c> appList = new List<AdjustPriceProduct__c>();
              appList = [select Product__c,OriginalPrice__c,AdjustSalesPrice__c  from AdjustPriceProduct__c where AdjustPrice__c =:apId];

              if(appList.size() == 0) return ap ;

              Set<Id> prodsets = new Set<Id>();
              for ( AdjustPriceProduct__c app: appList ) {
                    prodsets.add(app.Product__c);              
              }
              Map<String,PriceList__c> priceListMap = new Map<String,PriceList__c>();
              for (PriceList__c p :[select Id ,Product__c,Price__c,SalesCode__c ,ApplicableCustomers__c  from PriceList__c where  Account__c =:ap.Account__c and  SalesCode__c =:ap.SalesCode__c and Product__c in:prodsets ] ) {
                    
                    priceListMap.put(p.Product__c+'-'+p.SalesCode__c+'-'+p.ApplicableCustomers__c ,p);     
              }
              
              List<PriceList__c> plList = new List<PriceList__c>();
              for (AdjustPriceProduct__c app: appList) {

                     PriceList__c pl = null;
                   
                     String key = app.Product__c +'-'+ap.SalesCode__c +'-'+terminalId;

                    if(priceListMap.containsKey(key)){

                        pl = priceListMap.get(key );
                    }else{
                        pl = new PriceList__c();
                        pl.Product__c = app.Product__c;
                        pl.SalesCode__c = ap.SalesCode__c;
                        pl.JustPriceProduct__c = app.Id;
                        pl.Account__c = ap.Account__c;
                        

                        pl.ApplicableCustomers__c = terminalId;

                    }
                      pl.Company__c = ap.Company__c;
                 
                      pl.Price__c =  app.AdjustSalesPrice__c;
                      pl.OwnerId = ap.OwnerId;
                      plList.add(pl);



              }


                  
              if(plList.size() >0) upsert plList;
            return ap ;

  
            
    } 


    //  //如果 是工程部新建的 调价 共享给客户小组 及客户所有人 
    public static void shareToAccountUser(List<AdjustPrice__c> list_new ){
      System.debug('shareToAccountUser');
        Map<Id,Set<AdjustPrice__c>> apUserMap = new Map<Id,Set<AdjustPrice__c>>();

        for(AdjustPrice__c ap :list_new){
          Set<AdjustPrice__c> apset = apUserMap.containsKey(ap.CreatedById) ? apUserMap.get(ap.CreatedById) : new Set<AdjustPrice__c>();
          apset.add(ap);
          apUserMap.put(ap.CreatedById ,apset ) ;
        }

        //
        Map<Id,Id> apAccountMap = new Map<Id,Id>();
        Set<Id> existAPOwners = new Set<Id>();
        for(User u : [select Id from User where Id in: apUserMap.keySet() and Profile.Name like '%工程部%']){

          if(apUserMap.containsKey(u.Id )){
            for(AdjustPrice__c ap : apUserMap.get(u.Id)){
              apAccountMap.put(ap.Id,ap.Account__c);
              existAPOwners.add(ap.OwnerId);
            }
          }

        }

        if(apAccountMap.keySet().size() == 0) return; 
        apUserMap.clear();
        Map<Id,Set<Id>> accUserMap = new Map<Id,Set<Id>>();
        for(AccountTeamMember atm : [select AccountId,UserId  from AccountTeamMember where AccountId in:apAccountMap.values() and TeamMemberRole='同客户多人负责' ]){
          Set<Id> users =  accUserMap.containsKey(atm.AccountId ) ? accUserMap.get(atm.AccountId) : new Set<Id>();
          users.add(atm.UserId);
          accUserMap.put(atm.AccountId , users);
        }

        for(Account acc : [select Id, OwnerId from Account where Id in:apAccountMap.values() ]){
          Set<Id> users =  accUserMap.containsKey(acc.Id ) ? accUserMap.get(acc.Id ) : new Set<Id>();
          users.add(acc.OwnerId );
          accUserMap.put(acc.Id  , users);
        }

        List<AdjustPrice__Share> asList = new List<AdjustPrice__Share>();

       
        //共享权限
        for(Id apId  : apAccountMap.keySet() ){

          for(Id userId : accUserMap.get(apAccountMap.get(apId))){
              if(existAPOwners.contains(userId))continue;
              AdjustPrice__Share aps = new AdjustPrice__Share();
              aps.AccessLevel = 'Read';
              aps.UserOrGroupId = userId;
              aps.ParentId = apId; 
              asList.add(aps);

          }
        }
        System.debug(asList);
        if(asList.size() > 0 ) insert asList; 
    }

    /*public static void adjustPrice(List<AdjustPrice__c> newList, Map<Id, AdjustPrice__c> oldMap) {
        for (AdjustPrice__c q : newList) {
            AdjustPrice__c oldAdjustPrice = oldMap.get(q.Id);
            if (oldAdjustPrice.Status__c != q.Status__c && q.Status__c == '已批准') {
                // FIXME 审批只会一条一条来，所以允许在for循环里面写soql
                List<AdjustPriceProduct__c> fromList = [select Id, AdjustTo__c, AdjustSalesPrice__c from AdjustPriceProduct__c where AdjustPrice__c = :q.Id];
                Map<Id, AdjustPriceProduct__c> appMap = new Map<Id, AdjustPriceProduct__c>();
                for (AdjustPriceProduct__c app : fromList) {
                    appMap.put(app.AdjustTo__c, app);
                }

                List<ContractProduct__c> toList = [select Id from ContractProduct__c where Id in :appMap.keySet()];
                for (ContractProduct__c cp : toList) {
                    cp.SalesPrice__c = appMap.get(cp.Id).AdjustSalesPrice__c;
                    cp.PriceChanged__c = true;
                    cp.IsSycToNc__c = false;
                    // qp.Quantity__c = qpMap.get(qp.Id).Quantity__c;
                    // qp.Comment__c = qpMap.get(qp.Id).Comment__c;
                }
                update toList;
            }
        }
    }*/
}